package org.example.seata.bs.auth.handler.auth;

import cn.hutool.core.util.StrUtil;
import org.example.seata.bs.api.entity.account.AccountAuth;
import org.example.seata.common.security.constant.AuthTypeConst;
import org.example.seata.common.security.service.CustomUser;
import org.example.seata.common.security.util.MenuFacUtil;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @author hzq
 * @date 2021/12/6 13:18
 */
@Component
public class UsernameAuthHandler extends AbstractAuthHandler {

    /**
     * 处理两种登录方式
     * 自定义的
     * 1、grant_type=custom,handler_type=username
     * principal=用户名,credentials=密码
     * 官方的
     * 2、grant_type=password
     * username=用户名,password=密码
     */
    @Override
    public UserDetails handler(String principal, String credentials, Map<String, String> parameters) {

        AccountAuth auth = getNotNullAuth(principal);

        // 当凭证不为空时 即为自定义登录
        if (StrUtil.isNotEmpty(credentials)) {
            // 检验密码是否正确
            checkCredentials(credentials, auth.getCredentials());
        }

        // 检验用户信息
        checkAuth(auth);

        List<GrantedAuthority> userMenu = MenuFacUtil.getUserMenu(auth);

        return new CustomUser(auth, userMenu);
    }

    @Override
    public String getHandlerType() {
        return AuthTypeConst.USERNAME;
    }
}
